import java.net.*;
import java.io.*;
import java.lang.*;

public class MigrationManager implements Runnable 
{
	public void run()
	{
		Socket client = null;
		Agent agent = new Police("Police_Junix");
		try {
			client = new Socket("172.16.114.129",4567);
			migrate(client,agent);
		}catch(UnknownHostException ex){
			System.err.println(ex);
		} catch(IOException ex) {
			System.err.println(ex);
		}finally{
			try{
				if (client!=null)
					client.close();
			}catch (IOException ex){ }
		}
	}

	private void migrate(Socket sock, Agent agent)
	{
		ByteArrayOutputStream bout = null;
		ObjectOutputStream out=null;
		DataOutputStream dout=null;

		try{
			bout = new ByteArrayOutputStream();
			out = new ObjectOutputStream(bout);
			out.writeObject(agent);
		}catch (IOException ex) {
			System.err.println(ex);
		}finally{
			try{
				out.close();
			}catch(IOException ex) { }
		}

		try{
			byte[] bytes = bout.toByteArray();
			OutputStream os = sock.getOutputStream();
			dout = new DataOutputStream(os);
			int type = 1;
			dout.writeInt(type);

			//////////////////////////////////////////////////////
			writeClass(sock);
			//////////////////////////////////////////////////////
			//
			os.write(bytes);
		}catch(IOException ex){ }
	}

	private void  writeClass(Socket sock)
	{
		DataOutputStream out = null;
		try{
			out = new DataOutputStream(
					sock.getOutputStream());
			byte[] code = byteForClass("Police");
			out.writeInt(code.length);
			sock.getOutputStream().write(code);
		}catch (IOException e) { }
		catch (ClassNotFoundException e) { }
	}


	public byte[] byteForClass(String name)
		throws ClassNotFoundException
	{
		byte[] code = null;
		BufferedInputStream in = null;

		try{
			in = new BufferedInputStream(
					new FileInputStream("Police.class"));
			int length = in.available();
			if (length==0)
				throw new ClassNotFoundException(name);
			code = new byte[length];
			in.read(code,0,length);
		}catch(IOException ex){
			System.err.println(ex);
		}finally{
			if (in!=null)
				try{
					in.close();
				}catch(IOException ex){	}
		}

		return code;
	}

	public static void main(String[] args)
	{
		MigrationManager migration = new MigrationManager();
		Thread T = new Thread(migration);
		T.start();
	}

}
